<template>
  <div class="home-container">
    <!--    当属性默认值是false，可以直接写属性 显示true也可  :fixed="true"-->
    <van-nav-bar
      title="黑马头条"
      fixed
    />
    <!--    在使用组件的时候，如果某个属性名是小驼峰形式，则绑定属性的时候，建议改成连字符格式  cmtCount改写为 cmt-count -->
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :disabled="finished"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleInfo v-for="item in artlist"
                     :key="item.id"
                     :title="item.title"
                     :author="item.aut_name"
                     :cmt-count="item.comm_count"
                     :time="item.pubdate"
                     :cover="item.cover"
                     :type="item.cover.type"
                     :images="item.cover.images"
        ></ArticleInfo>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { getArticleListAPI } from '@/api/articleAPI'
import ArticleInfo from '@/components/article/ArticleInfo.vue'

export default {
  name: 'Home',
  components: {
    ArticleInfo
  },
  data () {
    return {
      page: 1,
      limit: 10,
      artlist: [],
      // 所有数据是否加载完毕，如果没有更多数据，一定要把finished改为true
      finished: false,
      // 每当下一页数据请求回来之后，把loading改为false
      loading: true,
      isLoading: false
    }
  },
  created () {
    this.initArticleList()
  },
  methods: {
    // 封装获取文章列表数据的方法 只要接口返回的是  promise实例，都可以通过async，await来优化
    async initArticleList (isRefresh) {
      const { data: res } = await getArticleListAPI(this.page, this.limit)
      if (isRefresh) {
        // 上拉刷新，新数据在前
        this.artlist = [...res, ...this.artlist]
        this.isLoading = false
      } else {
        // 上拉加载，新数据在后
        this.artlist = [...this.artlist, ...res]
        this.loading = false
      }

      if (res.length === 0) {
        // 证明没有下一页数据了，此时将finished改为true
        this.finished = true
      }
    },
    // 调用load事件，请求下一页数据
    onLoad () {
      this.page++
      this.initArticleList()
    },
    onRefresh () {
      this.page++
      this.initArticleList(true)
    }
  }
}
</script>

<style scoped lang="less">
.home-container {

  padding: 46px 0 50px 0;

  .van-nav-bar {
    background-color: #007bff;
  }

  /deep/ .van-nav-bar__title {
    color: white;
  }

}
</style>
